package com.zhangjun.chat.socket.handler;

import com.alibaba.fastjson.JSON;
import com.zhangjun.chat.application.UserService;
import com.zhangjun.chat.domain.user.model.UserInfo;
import com.zhangjun.chat.infrastructure.common.SocketChannelUtil;
import com.zhangjun.chat.protocol.talk.TalkNoticeRequest;
import com.zhangjun.chat.protocol.talk.TalkNoticeResponse;
import com.zhangjun.chat.socket.MyBizHandler;
import io.netty.channel.Channel;

import java.util.Date;

public class TalkNoticeHandler extends MyBizHandler<TalkNoticeRequest> {

    public TalkNoticeHandler(UserService userService) {
        super(userService);
    }

    @Override
    public void channelRead(Channel channel, TalkNoticeRequest msg) {
        logger.info("对话通知应答处理：{}", JSON.toJSONString(msg));
        // 判断是用户的对话框还是群组的对话框
        switch (msg.getTalkType()) {
            case 0:
                // 用户对话框,用户的对话框落库
                userService.addTalkBoxInfo(msg.getUserId(), msg.getFriendUserId(), 0);
                userService.addTalkBoxInfo(msg.getFriendUserId(), msg.getUserId(), 0);
                // 将自己发送给好友的对话框
                TalkNoticeResponse response = new TalkNoticeResponse();
                UserInfo userInfo = userService.queryUserInfo(msg.getUserId());
                response.setTalkId(userInfo.getUserId());
                response.setTalkName(userInfo.getUserNickName());
                response.setTalkHead(userInfo.getUserHead());
                response.setTalkSketch("你有新的消息");
                response.setTalkDate(new Date());
                // 获取朋友的管道
                Channel friendChannel = SocketChannelUtil.getChannel(msg.getFriendUserId());
                if (friendChannel == null) {
                    logger.info("对方不在线，无法发送通知");
                    return;
                }
                friendChannel.writeAndFlush(response);
                break;
            case 1:
                // 群组对话框,群组的对话框落库
                userService.addTalkBoxInfo(msg.getUserId(), msg.getFriendUserId(), 1);
                break;
            default:
                break;
        }

    }
}
